<script lang="ts" setup>
import lodash from 'lodash'
import moment from 'moment'
import { ActionBar, ActionBarButton, ActionBarIcon, Cell, CellGroup, Field, Picker, Popup, showFailToast, showSuccessToast } from 'vant'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { ContactApi } from '~/api/ContactApi'
import { JobRecordApi } from '~/api/JobRecordApi'
import { pickDate, protectedAction } from '~/utils'
import PairsView from '~/components/common/PairsView.vue'
import ContactPick from '~/components/order/edit/ContactPick.vue'
import { ContactModel, JobRecordModel } from '~/model'
import { JobAction } from '~/model/JobRecordModel'

const route = useRoute()
const router = useRouter()

enum Mode {
  None,
  Start,
  Event,
  Edit,
}

const id = ref(0)
const mode = ref(Mode.None)
const isNew = computed(() => mode.value !== Mode.Edit)
const record = ref(new JobRecordModel())
const records = ref([] as JobRecordModel[])
const contacts = ref([] as ContactModel[])
const pickingWorker = ref(false)
const pickingEvent = ref(false)

const obRecord = computed(() => {
  const workerOnBoardRecords = []

  const recordGroups = lodash.groupBy(records.value, x => x.worker!.uniqueName())
  for (const un of Object.keys(recordGroups)) {
    // const worker = contacts.value.find(x => x.uniqueName() === un)
    const recordGroup = recordGroups[un]
    recordGroup.sort((a, b) => a.id - b.id)
    let working = false
    let obRecord = null
    for (const record of recordGroup) {
      if (record.action === JobAction.End) {
        working = false
      }
      if (record.action === JobAction.Start) {
        working = true
        obRecord = record
      }
    }
    if (working) {
      workerOnBoardRecords.push(obRecord!)
    }
  }

  return workerOnBoardRecords
})
// 仅在职工人
const workers = computed(() => obRecord.value.map(x => x.worker!))
const notWorkers = computed(() => {
  const workersUn = workers.value.map(x => x.uniqueName())
  return contacts.value.filter(x => !workersUn.includes(x.uniqueName()))
})

onMounted(async () => {
  JobRecordApi.getAll()
    .then((res) => {
      records.value = res
      records.value.sort((a, b) => b.id - a.id)
    })

  const _id = route.query.id
  const _isStart = route.query.start
  const _isEvent = route.query.event

  const nEffecive = [
    _id, _isStart, _isEvent,
  ].map(x => (x ? 1 : 0) as number).reduce((y, x) => y + x, 0)
  if (nEffecive !== 1) {
    console.error(_id, _isStart, _isEvent)
    console.log([_id, _isStart, _isEvent].map(x => !!x))
  }
  if (_id) {
    mode.value = Mode.Edit
    id.value = Number.parseInt(_id as any)
    const records = await JobRecordApi.getAll()
    record.value = records.find(x => x.id === id.value) as JobRecordModel
  }
  else if (_isStart) {
    mode.value = Mode.Start
    record.value.action = JobAction.Start
    record.value.actionParams = [5000, '白班']
  }
  else if (_isEvent) {
    mode.value = Mode.Event

    const workerId = route.query.worker as string | undefined
    console.log(workerId)
    if (workerId) {
      const allContacts = await ContactApi.getAll()
      record.value.worker = allContacts.find(x => x.id === Number.parseInt(workerId))
      console.log(record.value.worker)
    }
  }

  if (mode.value === Mode.Start) {
    contacts.value = await ContactApi.getAll()
  }
})

async function handleSave() {
  const ok = isNew.value
    ? (
        await JobRecordApi.add(record.value)
      )
    : (
        await JobRecordApi.update(id.value, record.value)
      )
  if (ok) {
    showSuccessToast('操作成功')
    setTimeout(() => {
      router.replace('/jobs')
    })
  }
  else {
    showFailToast('操作失败')
  }
}

const eventOptions = [
  {
    value: JobAction.None,
    text: JobRecordModel.actionName(JobAction.None),
  },
  // 没有入职，因为入职的入口不在这
  // {
  //   value: JobAction.Start,
  //   text: xxxxxxxxxxxxxxx
  // },
  {
    value: JobAction.Pause,
    text: JobRecordModel.actionName(JobAction.Pause),
  },
  {
    value: JobAction.End,
    text: JobRecordModel.actionName(JobAction.End),
  },
  {
    value: JobAction.Schedule,
    text: JobRecordModel.actionName(JobAction.Schedule),
  },
  {
    value: JobAction.Bonus,
    text: JobRecordModel.actionName(JobAction.Bonus),
  },
  {
    value: JobAction.Blame,
    text: JobRecordModel.actionName(JobAction.Blame),
  },
  {
    value: JobAction.Advance,
    text: JobRecordModel.actionName(JobAction.Advance),
  },
  {
    value: JobAction.Settlement,
    text: JobRecordModel.actionName(JobAction.Settlement),
  },
]

const workerSource = computed(() => {
  let source: ContactModel[]
  if (record.value.action === JobAction.Start) {
    source = notWorkers.value
  }
  else {
    source = workers.value
  }
  return source
})

function handlePrint() {
  router.push(`/jobs/events/print?id=${record.value.id}`)
}

function eventPicked(e: { selectedOptions: any[] }) {
  pickingEvent.value = false
  console.log(e.selectedOptions)

  record.value.action = e.selectedOptions[0].value
  record.value.actionParams = []
}

const pickingSchedule = ref(false)
function schedulePicked(e: { selectedOptions: any[] }) {
  pickingSchedule.value = false
  if (record.value.action === JobAction.Start) {
    record.value.actionParams[1] = e.selectedOptions[0].value
  }
  else if (record.value.action === JobAction.Schedule) {
    record.value.actionParams[0] = e.selectedOptions[0].value
  }
}

async function switchDate() {
  const res = await pickDate(record.value.date)
  if (res) {
    record.value.date = res
  }
}

function onDelete() {
  protectedAction(() => {
    JobRecordApi.remove(id.value)
      .then((ok) => {
        if (ok) {
          showSuccessToast('删除成功')
          router.back()
        }
        else {
          showFailToast('删除失败，请联系管理员')
        }
      })
  }, '确定要删除事务吗', 0)
}

const hint = computed(() => {
  if (record.value.action === JobAction.End) {
    return '提示：离职日期指的是工作的最后一天，而不是没来的那天。'
  }
  else if (record.value.action === JobAction.Schedule) {
    return '提示：更改排期的日期请记录在新排期的那天，不要记录在旧排期的最后一天。'
  }
  else if (record.value.action === JobAction.Settlement) {
    return '提示：确认结清后工作记录将被分割。当前工作日等数据将会被清空'
  }
  else {
    return null
  }
})
</script>

<template>
  <div>
    <ContactPick
      v-if="workerSource"
      v-model="pickingWorker"
      v-model:consumer="record.worker"
      :source="workerSource"
    />

    <!-- 选择事务 -->
    <Popup
      v-model:show="pickingEvent"
      round
      position="bottom"
      title="选择事务"
    >
      <div>
        <Picker
          :columns="eventOptions"
          @cancel="pickingEvent = false"
          @confirm="eventPicked"
        />
      </div>
    </Popup>

    <!-- 选择排期 -->
    <Popup
      v-model:show="pickingSchedule"
      round
      position="bottom"
      title="选择事务"
    >
      <div>
        <Picker
          :columns="[
            { value: '白班', text: '白班' },
            { value: '夜班', text: '夜班' },
            { value: '其他', text: '其他' },
          ]"
          @cancel="pickingSchedule = false"
          @confirm="schedulePicked"
        />
      </div>
    </Popup>

    <!-- 姓名 -->
    <CellGroup mb2>
      <Cell
        title="姓名"
        :value="record.worker?.name ?? '(请选择)'"
        :is-link="true"
        @click="pickingWorker = true"
      />
    </CellGroup>

    <CellGroup mb2>
      <!-- 入职有唯一的入口，不能切换事务 -->
      <div v-if="record.action === JobAction.Start">
        <Field
          label="工资"
          type="digit"
          input-align="right"
          :model-value="record.actionParams[0]"
          @update:model-value="record.actionParams[0] = Number.parseInt($event)"
        />
        <Cell
          title="排期"
          :value="record.actionParams[1]"
          :is-link="true"
          @click="pickingSchedule = true"
        />
      </div>
      <!-- 非入职事务 -->
      <div v-else>
        <Cell
          title="事务"
          :value="record.actionName()"
          :is-link="true"
          @click="pickingEvent = true"
        />

        <div v-if="record.action === JobAction.End">
          <Field
            v-model="record.actionParams[0]"
            label="原因"
            input-align="right"
            placeholder="请填写原因"
          />
        </div>

        <div
          v-else-if="record.action === JobAction.Bonus
            || record.action === JobAction.Advance
            || record.action === JobAction.Blame"
        >
          <Field
            label="金额"
            type="digit"
            input-align="right"
            :model-value="record.actionParams[0]"
            placeholder="请填写金额"
            @update:model-value="record.actionParams[0] = Number.parseFloat($event)"
          />
          <Field
            v-model="record.actionParams[1]"
            label="原因"
            input-align="right"
            placeholder="请填写原因"
          />
        </div>
        <div
          v-else-if="record.action === JobAction.Pause"
        >
          <Field
            label="天数"
            type="number"
            input-align="right"
            :model-value="record.actionParams[0]"
            placeholder="请填写天数"
            @update:model-value="record.actionParams[0] = Number.parseFloat($event)"
          />
          <Field
            v-model="record.actionParams[1]"
            label="原因"
            input-align="right"
            placeholder="请填写原因"
          />
        </div>
        <div
          v-else-if="record.action === JobAction.Schedule"
        >
          <Cell
            title="排期"
            :value="record.actionParams[0]"
            :is-link="true"
            @click="pickingSchedule = true"
          />
        </div>
      </div>
    </CellGroup>

    <!-- 日期 -->
    <PairsView
      :pairs="[
        [
          '日期',
          moment(record.date).format('YYYY/MM/DD'),
          switchDate,
        ],
      ]"
    />

    <div v-if="hint" m2 paper bg-blue-1 b="1 solid blue" text-size-3 text-blue-5>
      {{ hint }}
    </div>

    <!-- 操作 -->
    <ActionBar>
      <ActionBarIcon
        v-if="mode === Mode.Edit && record.action === JobAction.Advance"
        text="打印" @click="handlePrint"
      >
        <template #icon>
          <FontAwesomeIcon icon="print" color="rgb(59, 130, 246)" />
        </template>
      </ActionBarIcon>

      <ActionBarIcon
        v-if="mode === Mode.Edit"
        text="删除" @click="onDelete"
      >
        <template #icon>
          <FontAwesomeIcon icon="trash-can" color="red" />
        </template>
      </ActionBarIcon>

      <ActionBarButton
        :color="mode === Mode.Edit ? 'dodgerblue' : 'mediumseagreen'"
        :text="mode === Mode.Edit ? '更改事务' : '创建事务'"
        @click="handleSave"
      />
    </ActionBar>
  </div>
</template>

<route lang="yaml">
meta:
  title: 事务
</route>
